#coding:utf-8
import wsgiref.handlers
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import users
import methods
import logging
from getimageinfo import getImageInfo

def format_date(dt):
    return dt.strftime('%a, %d %b %Y %H:%M:%S GMT')

class PublicPage(webapp.RequestHandler):
    def render(self, template_file, template_value):
        path = os.path.join(os.path.dirname(__file__), template_file)
        self.response.out.write(template.render(path, template_value))
    
    def error(self,code):
        if code==400:
            self.response.set_status(code)
        else:
            self.response.set_status(code)
            
    def is_admin(self):
        return users.is_current_user_admin()
    
    def head(self, *args):
        return self.get(*args) 
        
class GetFile(PublicPage):
    def get(self,id, name):
        file = methods.getFileByID(id)
        if not file:
            return self.error(404)
        self.response.headers['Content-Type'] = str(file.mime) 
        self.response.headers['Cache-Control']="max-age=315360000"
        self.response.headers['Last-Modified']=format_date(file.created_at)
        self.response.out.write(file.bf)

class ShowFile(PublicPage):
    def get(self,id, name):
        file = methods.getFileByID(id)
        if not file or file.isimage != 1:
            return self.error(404)
        
        filetype, width, height = getImageInfo(file.bf)
        template_value={"image":file, "filetype":filetype, "width":width, "height":height}
        self.render('views/show.html', template_value)


class Error(PublicPage):
    def get(self):
        return self.error(404)

def main():
    application = webapp.WSGIApplication(
                                       [
                                        (r'/file/down/(?P<id>[0-9]+)/(?P<name>.*)', GetFile),
                                        (r'/file/show/(?P<id>[0-9]+)/(?P<name>.*)', ShowFile)
                                       ], debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
    main()